const express = require("express");
const router = express.Router();
const config = require('../../config');
const utils = require('../../public/utils');
const formidable = require('formidable');
const path = require('path');
const fs = require('fs');


//上传接口
router.post('/upload',(req,res) => {
    utils.tokenValid(req,res,async() => {
        let pathStr = path.join(__dirname, '../../upload') ;
        let form = new formidable.IncomingForm(); //创建上传表单
        form.encoding = 'utf-8'; //设置编辑
        form.uploadDir = pathStr; //设置临时上传目录
        form.keepExtensions = true; //保留后缀
        form.maxFieldsSize = 2 * 1024 * 1024; //文件大小
        form.type = true;
        let fullPath;
        let type, nowPath;
        form.parse(req, function(err, fields, files) {
            if (err) {
                res.send(err);
                return;
            }
            var extName = ''; //后缀名
            for(let key in files) {
                if(files[key].type) {
                    type = files[key].type;
                    nowPath = files[key].path;
                }
            }

            switch (type) {
                case 'image/pjpeg':
                    extName = 'jpg';
                    break;
                case 'image/jpeg':
                    extName = 'jpg';
                    break;
                case 'image/png':
                    extName = 'png';
                    break;
                case 'image/x-png':
                    extName = 'png';
                    break;
            }

            if (extName.length === 0) {
                res.send(utils.setJsonStyle('9999', '只支持jpg和png格式！'));
            } else {
                let avatarName = '/' + Date.now() + '.' + extName;
                fullPath = config.source.sourceImgUrl + avatarName;
                fs.renameSync(nowPath, config.source.imgUploadPath + avatarName); //重命名和修改图片存放路径
                res.send(utils.setJsonStyle('0', '上传成功',{imgUrl: fullPath}));
            }
        });
    })


})

module.exports = router;